#encoding=utf8
'''
Created on May 8, 2015

@author: jingyang <jingyang@smalltreemedia.com>
'''
from django.db import models
from app_info.models import UserGroup, StudioCloud, Studio, APP_STORE,\
    ProductionTeam, AppVersion
from core.fields import CustomTextField
from core.widgets import CustomTextarea
from django.contrib.auth.models import User
from django.utils import timezone


ISSUED_BY = (
    ('N', 'nexa Design Team'),
    ('C', "Christy's Team"),
    ('T', 'Production Teams'),
    ('O', 'Other'),
)


STATUS = (
    ('P', 'Pending'),
    ('C', 'Confirmed'),
    ('D', 'Declined'),
    ('X', 'Cancelled'),
)


class ProductionOrderManager(models.Manager):
    def get_latest_num(self):
        current_year = timezone.now().year
        current_month = timezone.now().month
        current_day = timezone.now().day
        latest = self.filter(create_time__year=current_year, create_time__month=current_month,
            create_time__day=current_day).order_by('-order_id')[:1]
        return int(latest[0].order_id[-2:]) + 1 if latest else 1


class ProductionOrder(models.Model):
    order_id = models.CharField('Production Brief ID', max_length=20)
    editor = models.CharField('Created By', max_length=50)
    create_time = models.DateTimeField('Created At', auto_now_add=True)
    ref_num = models.CharField('Reference Number', max_length=200, null=True, blank=True)
    date_issued = models.DateField('Date Issued')
    date_received = models.DateField('Date Received')
    issued_by = models.CharField('Issued By', max_length=1, choices=ISSUED_BY,
        default='C')
    issued_by_text = models.CharField(max_length=100, null=True, blank=True)
    to = models.ForeignKey(UserGroup, verbose_name='Division')
    working_title = models.CharField('Project Working Title', max_length=1000)
    story_line = CustomTextField('Story Line', widget=CustomTextarea)
    mode = models.CharField('Mold', max_length=200, null=True, blank=True)
    studio_clouds = models.ForeignKey(StudioCloud, verbose_name='Studio Clouds')
    studio = models.ForeignKey(Studio, verbose_name='Studio')
    app_store = models.CharField('App Store', max_length=200, null=True, blank=True)
    content = CustomTextField('Structural Guidelines/Content', widget=CustomTextarea(
        attrs={'style': '''overflow: hidden; word-wrap: break-word; resize: horizontal;
                           width: 800px; height: 200px; max-height: 1200px;'''}),
        null=True, blank=True)
    reference = CustomTextField('Cultural/Visual References', widget=CustomTextarea(
        attrs={'style': '''overflow: hidden; word-wrap: break-word; resize: horizontal;
                           width: 800px; height: 200px; max-height: 1200px;'''}),
        null=True, blank=True)
    remarks = CustomTextField('Remarks', widget=CustomTextarea, null=True, blank=True)
    required_release_date = models.DateField('Required Release Date', null=True, blank=True)

    status = models.CharField('Confirmation Status', max_length=1, choices=STATUS,
        default='P', null=True, blank=True)
    assign_team = models.ForeignKey(ProductionTeam, null=True, blank=True,
        verbose_name='Assign to Production Team')
    assign_pjm = models.ForeignKey(User, verbose_name='Assign to PJM', null=True, blank=True,
        limit_choices_to={'is_active': True, 'is_staff': True})
    confirmed_date = models.DateField('Date of Confirmed', null=True, blank=True)

    objects = ProductionOrderManager()

    def __unicode__(self):
        return self.order_id

    def get_issued_by(self):
        if not self.issued_by == 'O':
            return self.get_issued_by_display()
        return self.issued_by_text

    def get_required_release_date(self):
        return self.required_release_date or 'Not Specified'

    def get_app_store(self):
        if self.app_store:
            return str(self.app_store).replace('[', '').replace(']', '').replace("u'", '')\
            .replace("'", '').split(', ')
        return ""

    def get_ref_num_title(self):
        return '%s%s%s' % (self.ref_num or '', ' - ' if self.ref_num else '',
            self.working_title)

    class Meta:
        verbose_name = 'Production Brief'
        verbose_name_plural = 'Production Brief'


class OrderStatusRecord(models.Model):
    order = models.ForeignKey(ProductionOrder, verbose_name='Production Order')
    editor = models.CharField('Editor', max_length=50)
    status_before = models.CharField('Status (Before)', max_length=1, choices=STATUS)
    status_after = models.CharField('Status (After)', max_length=1, choices=STATUS)
    time = models.DateTimeField('Time', auto_now_add=True)

    def __unicode__(self):
        return 'Status Record of Production Brief %s' % self.order

    class Meta:
        verbose_name = 'Production Brief Status Record'
        verbose_name_plural = 'Production Brief Status Records'


PROJECT_STATUS = (
    ('B', 'Wait to Start'),
    ('A', 'In Production'),
    ('X', 'Finished'),
    ('Z', 'Cancelled'),
    ('O', 'On Hold'),
)


JOB_FAMILY_MAP = {
    'PRD': '12,20,21',
    'Art': '50',
    'Content': '21',
    'UI/UE': '30',
    'Marketing Assets': '30',
    'Sound': '20,21',
    'Code': '40',
    'Dev QA': '60'
}


PROCEDURE_NAMES = (
    ('PRD', 'PRD'),
    ('Art', 'Art'),
    ('Content', 'Content'),
    ('UI/UE', 'UI/UE'),
    ('Marketing Assets', 'Marketing Assets'),
    ('Sound', 'Sound'),
    ('Code', 'Code'),
    ('Dev QA', 'Dev QA'),
)


TIER_CHOICES = (
    ('T0', 'T0'),
    ('T1', 'T1'),
    ('T2', 'T2'),
    ('T3', 'T3'),
    ('T4', 'T4'),
)


class ProjectManager(models.Manager):
    def get_latest_num(self):
        current_year = timezone.now().year
        current_month = timezone.now().month
        current_day = timezone.now().day
        latest = self.filter(created_time__year=current_year, created_time__month=current_month,
            created_time__day=current_day).order_by('-prj_id')[:1]
        return int(latest[0].prj_id[-2:]) + 1 if latest else 1


class Project(models.Model):
    order = models.OneToOneField(ProductionOrder, verbose_name='Production Brief',
        null=True, blank=True)
    status = models.CharField('Status', max_length=1, choices=PROJECT_STATUS,
        default='B')
    plan_start = models.DateField('Planned Start Date', null=True, blank=True)
    plan_end = models.DateField('Planned Finish Date', null=True, blank=True)
    real_start = models.DateField('Actual Start Date', null=True, blank=True)
    tasks = models.ManyToManyField(AppVersion, verbose_name='Production Tasks',
        null=True, blank=True)
    proce = models.CharField('Procedure', max_length=500, null=True, blank=True)
    created_time = models.DateTimeField('Created At', auto_now_add=True)
    editor = models.CharField('Created By', max_length=100, null=True, blank=True)

    prj_id = models.CharField('Project ID', max_length=20)
    division = models.ForeignKey(UserGroup, verbose_name='Division')
    team = models.ForeignKey(ProductionTeam, verbose_name='Production Team', null=True, blank=True)
    pjm = models.ForeignKey(User, verbose_name='Responsible PJM',
        limit_choices_to={'is_active': True, 'is_staff': True}, null=True, blank=True)
    working_title = models.CharField('Working Title', max_length=1000)

    tier = models.CharField('Tier', max_length=5, choices=TIER_CHOICES)
    studio = models.ForeignKey(Studio, verbose_name='Studio', null=True, blank=True)

    objects = ProjectManager()

    def __unicode__(self):
        return self.prj_id

    def get_proce(self):
        if self.proce and not self.proce == '[]':
            return str(self.proce).replace('[', '').replace(']', '').replace("u'", '')\
            .replace("'", '').split(', ')
        return ""

    class Meta:
        verbose_name = 'Project'
        verbose_name_plural = 'Project Tracker'
        ordering = ('status',)


PROGRESS = (
    ('WTS', 'WTS'),
    ('WIP', 'WIP'),
    ('DONE', 'DONE'),
)


class Procedure(models.Model):
    project = models.ForeignKey(Project, verbose_name='Project')
    name = models.CharField('Name', max_length=30)
    staffing = models.CharField('Staffing', max_length=2000, null=True, blank=True)
    progress = models.CharField('Progress', max_length=5, choices=PROGRESS, default='WTS')

    def get_staffing(self):
        return [x.split(' - ')[1] for x in self.staffing.split(',')] if self.staffing else ['TBD']

    def __unicode__(self):
        return 'Procedure %s of %s' % (self.name, self.project)
